package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.common.consts.RedisConst;
import com.atguigu.gmall.common.util.JSONStr;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.model.vo.user.LoginUserResponseVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @author Dell
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2022-05-31 10:45:53
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public LoginUserResponseVo login(UserInfo userInfo) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name",userInfo.getLoginName());
        String pass = MD5.encrypt(userInfo.getPasswd());
        queryWrapper.eq("passwd",pass);
        UserInfo info = baseMapper.selectOne(queryWrapper);
        if (info== null){
            return null;
        }
        //设置IP地址，防止用户篡改token
        info.setIpAddr(userInfo.getIpAddr());

        LoginUserResponseVo loginUserResponseVo = new LoginUserResponseVo();
        String token = saveUserAuthInfo(info);
        loginUserResponseVo.setToken(token);
        loginUserResponseVo.setNickName(info.getNickName());

        return loginUserResponseVo;
    }

    @Override
    public String saveUserAuthInfo(UserInfo userInfo) {
        String token = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_PREFIX+token, JSONStr.toJsonStr(userInfo),7, TimeUnit.DAYS);
        return token;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(RedisConst.USER_LOGIN_PREFIX+token);
    }
}




